<template>
  <div class="user-list-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" @click="openAddDialog">新增用户</el-button>
    </div>

    <!-- 搜索 -->
    <div class="search-filter">
      <el-input
        v-model="searchUsername"
        placeholder="请输入用户名"
        style="width: 200px; margin-right: 10px;"
        clearable
      />
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>

    <!-- 用户列表 -->
    <el-table :data="userList.records" style="width: 100%" v-loading="loading">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="用户ID" width="80" />
      <el-table-column label="头像" width="120">
        <template #default="scope">
          <div style="display: flex; align-items: center; gap: 8px;">
            <img 
              :src="scope.row.avatar || getDefaultAvatar(scope.row.id)" 
              alt="用户头像" 
              style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover; cursor: pointer;"
              @click="handleAvatarDownload(scope.row.avatar || getDefaultAvatar(scope.row.id), scope.row.username)"
              title="点击下载头像"
            />
            <el-button 
              type="text" 
              size="small"
              @click="handleAvatarDownload(scope.row.avatar || getDefaultAvatar(scope.row.id), scope.row.username)"
              title="下载头像"
            >
              下载
            </el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" width="150" />
      <el-table-column prop="nickname" label="昵称" width="120" />
      <el-table-column prop="phone" label="手机号码" width="150" />
      <el-table-column prop="email" label="邮箱" width="200" :show-overflow-tooltip="true" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="primary" link @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="userList.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        label-width="100px"
        style="max-width: 400px;"
      >
        <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        
        <el-form-item 
          v-if="!userForm.id"
          label="密码" 
          prop="password" 
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
        >
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userForm.nickname" placeholder="请输入昵称" />
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="头像">
          <div style="display: flex; align-items: center; gap: 20px; flex-wrap: wrap;">
            <!-- 预览头像 -->
            <img 
              v-if="userForm.avatar"
              :src="userForm.avatar" 
              alt="用户头像" 
              style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 2px solid #e0e0e0; cursor: pointer;"
              @click="handleAvatarDownload(userForm.avatar, userForm.username || 'user')"
              title="点击下载头像"
            />
            <img 
              v-else
              :src="userForm.id ? getDefaultAvatar(userForm.id) : getDefaultAvatar(0)"
              alt="默认头像"
              style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 2px solid #e0e0e0; cursor: pointer;"
              @click="handleAvatarDownload(userForm.id ? getDefaultAvatar(userForm.id) : getDefaultAvatar(0), userForm.username || 'user')"
              title="点击下载头像"
            />
            
            <div style="display: flex; flex-direction: column; gap: 10px;">
              <!-- 头像上传组件 -->
              <el-upload
                :show-file-list="false"
                :before-upload="handleAvatarUpload"
                accept="image/*"
              >
                <el-button type="primary" :icon="Upload">
                  上传头像
                </el-button>
              </el-upload>
              
              <!-- 头像下载按钮 -->
              <el-button 
                type="default" 
                size="small"
                @click="handleAvatarDownload(userForm.avatar || (userForm.id ? getDefaultAvatar(userForm.id) : getDefaultAvatar(0)), userForm.username || 'user')"
              >
                下载头像
              </el-button>
            </div>
          </div>
        </el-form-item>
        

      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElUpload } from 'element-plus';
import { Upload } from '@element-plus/icons-vue';
import {
  listUsers,
  getUser,
  createUser,
  updateUser,
  deleteUsers,
  uploadAvatar,
  getAvatarUrl
} from '@/api/user';

// 定义用户类型
interface User {
  id: number;
  username: string;
  password?: string;
  nickname: string;
  phone: string;
  email: string;
  avatar?: string;
  createTime: string;
  avatarUrl?: string;
}

// 表格数据
const userList = ref({ records: [] as User[], total: 0 });
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索
const searchUsername = ref('');

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('新增用户');
const userFormRef = ref();
const userForm = reactive({
  id: null,
  username: '',
  password: '',
  nickname: '',
  phone: '',
  email: '',
  avatar: ''
});

// 头像占位图 - 使用随机头像服务
const getDefaultAvatar = (id: number) => {
  return `https://api.dicebear.com/7.x/personas/svg?seed=user${id}`;
};

// 加载用户列表 - 调用真实API
const loadUserList = async () => {
  loading.value = true;
  
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      username: searchUsername.value
    };
    
    const response = await listUsers(params);
    
    // 处理响应数据
    if (response.data && response.data.data) {
      userList.value = response.data.data;
      
      // 为每个用户添加头像URL
      userList.value.records.forEach(user => {
        if (!user.avatar) {
          user.avatar = getDefaultAvatar(user.id);
        } else if (user.avatar && !user.avatar.startsWith('data:image/') && !user.avatar.startsWith('http')) {
          user.avatar = getAvatarUrl(user.id);
        }
      });
    }
    
    ElMessage.success('用户列表加载成功');
  } catch (error) {
    ElMessage.error('加载用户列表时出错');
    console.error('加载用户列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索用户
const handleSearch = () => {
  try {
    // 重置到第一页
    currentPage.value = 1;
    
    // 直接调用加载用户列表函数
    loadUserList();
    
    ElMessage.success('搜索成功');
  } catch (error) {
    ElMessage.error('搜索失败');
    console.error('搜索用户失败:', error);
  }
};

// 重置搜索
const resetSearch = () => {
  searchUsername.value = '';
  currentPage.value = 1;
  loadUserList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  loadUserList();
};

// 当前页变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current;
  loadUserList();
};

// 打开新增对话框
const openAddDialog = () => {
  dialogTitle.value = '新增用户';
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑对话框
const openEditDialog = async (row: User) => {
  dialogTitle.value = '编辑用户';
  loading.value = true;
  
  try {
    // 调用API获取用户详情
    const response = await getUser(row.id);
    
    if (response.data && response.data.data) {
      // 复制用户数据，但不包含密码
      const formData = { ...response.data.data };
      delete formData.password; // 不显示密码
      
      // 处理头像
      if (formData.avatar && !formData.avatar.startsWith('data:image/') && !formData.avatar.startsWith('http')) {
        formData.avatar = getAvatarUrl(formData.id);
      }
      
      Object.assign(userForm, formData);
      dialogVisible.value = true;
    }
  } catch (error) {
    ElMessage.error('加载用户详情失败');
    console.error('加载用户详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  userForm.id = null;
  userForm.username = '';
  userForm.password = '';
  userForm.nickname = '';
  userForm.phone = '';
  userForm.email = '';
  userForm.avatar = '';
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

// 处理头像上传
const handleAvatarUpload = async (rawFile: File) => {
  // 检查文件类型
  const isImage = /^image\//.test(rawFile.type);
  if (!isImage) {
    ElMessage.error('请上传图片文件!');
    return false;
  }

  // 检查文件大小（限制2MB）
  const isLt2M = rawFile.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!');
    return false;
  }

  if (!userForm.id) {
    // 如果是新增用户，先使用本地预览
    try {
      const reader = new FileReader();
      reader.readAsDataURL(rawFile);
      reader.onload = (e) => {
        userForm.avatar = e.target?.result as string;
      };
      
      ElMessage.success('头像预览已更新，创建用户后会自动上传');
    } catch (error) {
      ElMessage.error('头像预览失败，请重试');
      console.error('头像预览错误:', error);
    }
  } else {
    // 如果是编辑用户，直接上传到服务器
    try {
      loading.value = true;
      const response = await uploadAvatar(rawFile, userForm.id);
      
      if (response.data && response.data.code === 200) {
        // 获取上传后的头像URL
        userForm.avatar = getAvatarUrl(userForm.id);
        ElMessage.success('头像上传成功');
      }
    } catch (error) {
      ElMessage.error('头像上传失败，请重试');
      console.error('头像上传错误:', error);
    } finally {
      loading.value = false;
    }
  }
  
  // 阻止默认上传行为
  return false;
};

// 处理头像下载
const handleAvatarDownload = (avatarUrl: string, username: string) => {
  // 对于base64格式的头像，直接下载
  if (avatarUrl.startsWith('data:image/')) {
    try {
      // 创建一个临时的a标签
      const link = document.createElement('a');
      link.href = avatarUrl;
      link.download = `${username}_avatar.png`;
      // 触发下载
      document.body.appendChild(link);
      link.click();
      // 清理
      document.body.removeChild(link);
      ElMessage.success('头像下载成功');
    } catch (error) {
      ElMessage.error('头像下载失败，请重试');
      console.error('头像下载错误:', error);
    }
  } else {
    // 对于URL格式的头像，使用fetch API下载
    fetch(avatarUrl)
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.blob();
      })
      .then(blob => {
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        // 确定文件扩展名
        const fileExtension = avatarUrl.includes('.svg') ? 'svg' : 'png';
        link.download = `${username}_avatar.${fileExtension}`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        ElMessage.success('头像下载成功');
      })
      .catch(error => {
        ElMessage.error('头像下载失败，请重试');
        console.error('头像下载错误:', error);
      });
  }
};

// 提交表单
const handleSubmit = async () => {
  if (!userFormRef.value) return;
  
  try {
    await userFormRef.value.validate();
    
    // 创建一个副本，避免修改原始数据
    const formData = { ...userForm };
    
    // 如果是编辑模式且没有输入新密码，不发送密码字段
    if (formData.id && !formData.password) {
      delete formData.password;
    }
    
    if (formData.id) {
      // 编辑模式
      const response = await updateUser(formData);
      
      if (response.data && response.data.code === 200) {
        ElMessage.success('用户更新成功');
        dialogVisible.value = false;
        // 刷新列表
        loadUserList();
      }
    } else {
      // 新增模式
      // 确保有密码
      if (!formData.password) {
        ElMessage.warning('新增用户必须设置密码');
        return;
      }
      
      const response = await createUser(formData);
      
      if (response.data && response.data.code === 200) {
        ElMessage.success('用户创建成功');
        dialogVisible.value = false;
        // 刷新列表
        loadUserList();
      }
    }
  } catch (error) {
    ElMessage.error('操作失败，请重试');
    console.error('用户操作失败:', error);
  }
};

// 删除用户
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await deleteUsers([id]);
    
    if (response.data && response.data.code === 200) {
      ElMessage.success('用户删除成功');
      // 刷新用户列表
      loadUserList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除用户失败');
      console.error('删除用户失败:', error);
    } else {
      ElMessage.info('已取消删除');
    }
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadUserList();
});
</script>

<style scoped>
.user-list-container {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.search-filter {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>